package com.teatrace.service.impl;

import javax.jws.WebService;

import com.dao.genericdao.IBaseDao;
import com.teatrace.model.Product;
import com.teatrace.model.TraceInfo;
import com.teatrace.service.RFIDDataSyncService;
import com.teatrace.service.utils.BeanUtil;

@WebService(endpointInterface="com.teatrace.service.RFIDDataSyncService")
public class RFIDDataSyncServiceImpl implements RFIDDataSyncService{

	private IBaseDao<Product, Integer> productDao;
	private IBaseDao<TraceInfo, Integer> traceInfoDao;
	
	@Override
	public void syncProductInfo(Product product) {
		Integer id = product.getId();
		if(id == null) {
			productDao.save(product);
		} else {
			Product productFromDB = productDao.getById(id);
			BeanUtil.copyDeclaredFieldIgnoreNull(product, productFromDB, Product.class);
		}
	}

	@Override
	public void syncTraceInfo(TraceInfo traceInfo, String productNumber) {
		Integer id = traceInfo.getId();
		Product product = productDao.findByNamedParams("from Product where productNum=:productNum", new String[]{"productNum"}, productNumber).get(0);
		traceInfo.setProductId(product.getId());
		if(id != null) {
			TraceInfo traceInfoFromDB = traceInfoDao.getById(id);
			BeanUtil.copyDeclaredFieldIgnoreNull(traceInfo, traceInfoFromDB, TraceInfo.class);
			product.getTraceInfoSet().add(traceInfoFromDB);
			productDao.save(product);
		} else {
			product.getTraceInfoSet().add(traceInfo);
			traceInfoDao.save(traceInfo);
			productDao.save(product);
		}
	}

	public IBaseDao<Product, Integer> getProductDao() {
		return productDao;
	}

	public void setProductDao(IBaseDao<Product, Integer> productDao) {
		this.productDao = productDao;
		this.productDao.setEntityClass(Product.class);
	}

	public IBaseDao<TraceInfo, Integer> getTraceInfoDao() {
		return traceInfoDao;
	}

	public void setTraceInfoDao(IBaseDao<TraceInfo, Integer> traceInfoDao) {
		this.traceInfoDao = traceInfoDao;
		this.traceInfoDao.setEntityClass(TraceInfo.class);
	}
	
	

}
